Page({
  data: {
    messages: [],
    inputContent: '',
    consultantInfo: null,
    userInfo: null,
    lastMessageId: '',
    websocket: null
  },

  onLoad(options) {
    console.log('聊天页面接收到的参数:', options);
    const { consultantId, courseId } = options;
    
    if (!consultantId) {
        console.error('未接收到咨询师ID');
        wx.showToast({
            title: '参数错误',
            icon: 'none'
        });
        return;
    }
    
    console.log('准备加载咨询师信息, ID:', consultantId);
    // 获取用户信息
    const userInfo = wx.getStorageSync('user');
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    this.setData({
      userInfo,
    });

    // 获取咨询师信息
    this.loadConsultantInfo(consultantId);
    
    // 连接WebSocket
    this.connectWebSocket(userInfo.userId);
  },

  // 加载咨询师信息
  loadConsultantInfo(consultantId) {
    console.log('开始请求咨询师信息:', consultantId);
    wx.request({
      url: `http://120.26.112.194:80/api/admin/courses/detailIntroduce?id=${consultantId}`,
      method: 'GET',
      success: (res) => {
        console.log('咨询师信息返回:', res.data);
        if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
          const consultantInfo = res.data.data[0];
          console.log('解析后的咨询师信息:', consultantInfo);
          this.setData({ consultantInfo });
          // 设置导航栏标题
          wx.setNavigationBarTitle({
            title: `与${consultantInfo.consultantName}的对话`
          });
        }
      },
      fail: (err) => {
        console.error('获取咨询师信息失败:', err);
        wx.showToast({
          title: '获取咨询师信息失败',
          icon: 'none'
        });
      }
    });
  },

  // 连接WebSocket
  connectWebSocket(userId) {
    if (this.data.websocket) {
      console.log('WebSocket 已连接，无需重新连接');
      return;
    }

    const wsUrl = `ws://120.26.112.194:80/apii/websocket/chat?userId=${userId}`;
    console.log('正在连接WebSocket:', wsUrl);
    
    const ws = wx.connectSocket({
      url: wsUrl,
      success: () => {
        console.log('WebSocket连接成功');
      }
    });

    ws.onOpen(() => {
      console.log('WebSocket连接已打开');
      this.setData({ websocket: ws });
    });

    ws.onMessage((res) => {
      try {
        console.log('收到WebSocket消息:', res.data);
        const message = JSON.parse(res.data);
        
        // 添加到消息列表
        const messages = [...this.data.messages, {
          id: Date.now(),
          content: message.content,
          isSelf: false,
          timestamp: message.timestamp,
          senderAvatar: message.senderAvatar,
          type: message.type || 'wx'  // 确保有消息类型
        }];
        
        // 立即更新界面
        this.setData({ 
          messages,
          lastMessageId: `msg-${messages[messages.length - 1].id}`
        }, () => {
          // 滚动到最新消息
          this.scrollToBottom();
        });
        
      } catch (error) {
        console.error('处理消息失败:', error);
      }
    });

    ws.onClose(() => {
      console.log('WebSocket连接已关闭');
      this.setData({ websocket: null });
    });

    ws.onError((error) => {
      console.error('WebSocket连接错误:', error);
      this.setData({ websocket: null });
    });
  },

  // 输入框内容变化
  onInput(e) {
    this.setData({
      inputContent: e.detail.value
    });
  },

  // 发送消息
  sendMessage() {
    if (!this.data.inputContent.trim() || !this.data.websocket) {
      return;
    }

    const userInfo = wx.getStorageSync('user');
    console.log('发送消息时的用户信息：', userInfo);

    const message = {
      senderId: userInfo.userId,
      senderName: userInfo.userName,
      senderAvatar: userInfo.userAvatar,
      receiverId: this.data.consultantInfo.consultantId,
      content: this.data.inputContent.trim(),
      timestamp: Date.now(),
      type: 'wx'
    };

    console.log('准备发送的消息：', message);

    this.data.websocket.send({
      data: JSON.stringify(message),
      success: () => {
        // 添加到本地消息列表并立即更新界面
        const messages = [...this.data.messages, {
          id: Date.now(),
          content: message.content,
          isSelf: true,
          timestamp: message.timestamp,
          senderAvatar: userInfo.userAvatar,
          type: 'wx'
        }];
        
        this.setData({
          messages,
          inputContent: '',
          lastMessageId: `msg-${messages[messages.length - 1].id}`
        }, () => {
          // 滚动到最新消息
          this.scrollToBottom();
        });
      }
    });
  },

  onUnload() {
    // 页面卸载时关闭WebSocket连接
    if (this.data.websocket) {
      this.data.websocket.close();
    }
  },

  // 修改 WebSocket 消息处理
  onMessage(res) {
    try {
      console.log('收到消息：', res.data);
      const message = JSON.parse(res.data);
      
      if (message.code === 200 && message.data) {
        const messageData = message.data;
        const messages = [...this.data.messages, {
          id: Date.now(),
          content: messageData.content,
          isSelf: false,
          timestamp: messageData.timestamp,
          senderAvatar: messageData.senderAvatar  // 保存发送者头像
        }];
        
        this.setData({ 
          messages,
          lastMessageId: `msg-${messages[messages.length - 1].id}`
        });
      }
    } catch (error) {
      console.error('处理消息失败：', error);
    }
  },

  // 添加滚动到底部的方法
  scrollToBottom() {
    wx.createSelectorQuery()
      .select('#message-list')
      .boundingClientRect((rect) => {
        if (rect) {
          wx.pageScrollTo({
            scrollTop: rect.height,
            duration: 300
          });
        }
      })
      .exec();
  }
}); 